package cc.fs.zhihuapp.ui.activity.demo;

import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.view.View;
import android.widget.GridLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;

import cc.fs.zhihuapp.R;
import cc.fs.zhihuapp.utils.ClickableTextViewMentionLinkOnTouchListener;
import cc.fs.zhihuapp.utils.MySpan;

/**
 * Created by fostion on 2015/8/31.
 */
public class MySpanActivity extends AppCompatActivity {

    String pic1 = "http://img1.imgtn.bdimg.com/it/u=3229727480,642457655&fm=21&gp=0.jpg";
    String pic2 = "http://img2.imgtn.bdimg.com/it/u=2199180302,1055708820&fm=21&gp=0.jpg";
    String pic3 = "http://img0.imgtn.bdimg.com/it/u=48252272,1629415252&fm=21&gp=0.jpg";
    String pic4 = "http://img5.imgtn.bdimg.com/it/u=1089045078,3032373419&fm=21&gp=0.jpg";

    String myText = "我要识别的网址是 http://www.baidu.com/,我要识别的#狗凡是逗逼#,我要识别的是//@喷我会生气：这是一个比较长的字符串";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_test);

        GridLayout layout1 = (GridLayout)findViewById(R.id.imglayout1);
        GridLayout layout2 = (GridLayout)findViewById(R.id.imglayout2);
        TextView textView = (TextView)findViewById(R.id.text);

        ((SimpleDraweeView)layout1.getChildAt(0)).setImageURI(Uri.parse(pic1));
        ((SimpleDraweeView)layout1.getChildAt(1)).setImageURI(Uri.parse(pic2));
        ((SimpleDraweeView)layout1.getChildAt(2)).setImageURI(Uri.parse(pic3));


        ((SimpleDraweeView)layout2.getChildAt(0)).setImageURI(Uri.parse(pic4));
        ((SimpleDraweeView)layout2.getChildAt(1)).setVisibility(View.GONE);
        ((SimpleDraweeView)layout2.getChildAt(2)).setVisibility(View.INVISIBLE);

        SpannableString spanString = SpannableString.valueOf(myText);
        Linkify.addLinks(spanString, MySpan.MySpanPattern.WEB_URL, MySpan.MySpanPattern.SCHEME100);
        Linkify.addLinks(spanString, MySpan.MySpanPattern.TOPIC_URL, MySpan.MySpanPattern.SCHEME200);
        Linkify.addLinks(spanString, MySpan.MySpanPattern.MENTION_URL, MySpan.MySpanPattern.SCHEME300);

        //识别出来和替换成可点击的变量
        URLSpan[] urlSpans = spanString.getSpans(0, spanString.length(), URLSpan.class);
        MySpan tempSpan = null;
        for (URLSpan urlSpan : urlSpans) {
            tempSpan = new MySpan(urlSpan.getURL());
            int start = spanString.getSpanStart(urlSpan);
            int end = spanString.getSpanEnd(urlSpan);
            spanString.removeSpan(urlSpan);
            spanString.setSpan(tempSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        textView.setText(spanString);
        textView.setOnTouchListener(new ClickableTextViewMentionLinkOnTouchListener());
    }


}
